package com.twxm.breed.service;

import com.twxm.breed.entity.DissolvedOxygen;
import com.twxm.breed.entity.FishPond;
import com.twxm.breed.mapper.DissolvedOxygenMapper;
import com.twxm.breed.mapper.FishPondMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DissolvedOxygenService {
    @Autowired
    private DissolvedOxygenMapper dissolvedOxygenMapper;
    @Autowired
    private FishPondMapper fishPondMapper;

    @Transactional(rollbackFor = Exception.class)
    public void insertList(List<HashMap<String,String>> list) throws Exception {
        for (int i = 0; i< list.size(); ++i){
            Date date = new Date();
            float oxygen = 0;
            String pondId = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            for (String key: list.get(i).keySet()){
                if (key.equals("溶氧量")||key.equals("oxygen")){
                    oxygen = Float.parseFloat(list.get(i).get(key));
                }else if(key.equals("采集地点")){
                    pondId =list.get(i).get(key);
                }else{
                    date = simpleDateFormat.parse(list.get(i).get(key));
                }
            }
            FishPond fishPond = fishPondMapper.selectById(pondId);
            DissolvedOxygen dissolvedOxygen = new DissolvedOxygen(oxygen,date,fishPond);
            if (dissolvedOxygenMapper.selectIdByPondIdAndCollectionTime(dissolvedOxygen) == null) {
                dissolvedOxygenMapper.insertDissolvedOxygen(dissolvedOxygen);
            }else {
                dissolvedOxygenMapper.updateDissolvedOxygen(dissolvedOxygen);
            }
        }
    }

    public List<DissolvedOxygen> getByPondId(String pondId) {
        return dissolvedOxygenMapper.getByPondId(pondId);
    }

    public List<DissolvedOxygen> getOxygenInfo(String el) {
        return dissolvedOxygenMapper.getOxygenInfo(el);
    }

    public List<String> getPondId(){ return dissolvedOxygenMapper.getPondId(); }

    public List<DissolvedOxygen> getByPondIdAndDate(Map<String, Object> map) {
        return dissolvedOxygenMapper.getByPondIdAndDate(map);
    }

    public List<DissolvedOxygen> getOxygenInfoByDate(Date date) {
        return dissolvedOxygenMapper.getOxygenByDate(date);
    }

    public Float getLatestOxygenByPondId(String pondId){
        return dissolvedOxygenMapper.getLatestOxygenByPondId(pondId);
    }
}
